package com.beone.smart.gateway.config;

import com.alibaba.fastjson.JSON;
import com.beone.smart.gateway.feign.UserFeignClient;
import com.beone.smart.gateway.result.ResultEntity;
import com.beone.smart.gateway.result.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.DispatcherHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @Date: 2019/8/8
 * @Author: yangjie
 * desc:  token校验拦截
 **/
@Component
@Slf4j
public class TokenFilter implements GlobalFilter, Ordered {
    @Autowired
    private UserFeignClient userFeignClient;

    private final ObjectProvider<DispatcherHandler> dispatcherHandler;

    public TokenFilter(ObjectProvider<DispatcherHandler> dispatcherHandler) {
        this.dispatcherHandler = dispatcherHandler;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange webExchange, GatewayFilterChain filterChain) {
        ResultEntity resultEntity = null;
        boolean status = true;
        ServerHttpRequest httpRequest = webExchange.getRequest();
        String currentURL = httpRequest.getURI().toString();
        String ticket = httpRequest.getQueryParams().getFirst("ticket");
        log.error("当前请求的url:{}", currentURL);
        log.error("当前请求的参数:{}", httpRequest.getQueryParams());
        if (currentURL.contains("/template/get_by_id/")) {
            resultEntity = userFeignClient.getSysUserInfoByKey(ticket);
            if (resultEntity.getData() == null) {
                return setFailedRequest(webExchange, ResultTool.fail(ResultTool.HttpResponseCode.NOT_LOGIN, "登录认证信息失效"));
            }
        }
        if (status) {
            //向headers中放文件，记得build
            ServerHttpRequest host = webExchange.getRequest().mutate().header("token", "123514325").build();
            //将现在的request 变成 change对象
            ServerWebExchange build = webExchange.mutate().request(host).build();
            return filterChain.filter(build);
        } else {
            return setFailedRequest(webExchange, ResultTool.fail(ResultTool.HttpResponseCode.NOT_LOGIN, "登录信息失效"));
        }
    }

    @Override
    public int getOrder() {
        return -1000;
    }

    /**
     * 返回未登录提示信息
     */
    private Mono<Void> setFailedRequest(ServerWebExchange exchange, Object object) {
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(object));
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
